import json
class MysqlDatabases:
    def __init__(self):
        #读取配置文件里的信息

        with open('TeacherUsernameAndpassword.txt', 'r') as file:
            lines=file.readlines()
            lines=[line.replace('\n', '') for line in lines]
            #<class 'list'>: ['{"password": "888", "username": "teacher1"}\n', '{"username": "teacher2", "password": "qwer1234"}\n']
        self.users=lines
        self.students=json.loads(open("StudentAchievements.txt",mode='r',encoding='utf-8').read())

    def check_login(self,username,password):
        for user in self.users:
            i=1
            #user是str,jsonload后变成字典
            if username==json.loads(user)['username']:
                if password==json.loads(user)['password']:
                    return True,'登陆成功'
                else:
                    return False,'登录失败，用户不存在'
        return False,"登录失败，用户不存在"

    def all(self):
        i=1
        return self.students

    def insert(self, student):
        i=1
        #此时已经增加成功了
        self.students.append(student)
        #将student写入StudentAchievements.txt里,持久化存储
        with open('StudentAchievements.txt', 'w',encoding='utf-8') as file:
            json.dump(self.students, file)

    def delete_by_username(self,name):
        for student in self.students:
            #print(student)
            if student['name']==name:
                self.students.remove(student)
                with open('StudentAchievements.txt', 'w', encoding='utf-8') as file:
                    json.dump(self.students, file)
                return True,'{}用户删除成功'.format(name)
        return False,'{}用户不存在'.format(name)

    def search_by_username(self,name):
        for student in self.students:
            if student['name']==name:
                return True,student
        return False,'{}用户不存在'.format(name)

    def update(self,stu):
        for student in self.students:
            if student['name']==stu['name']:
                #字典值更新
                student.update(stu)
                with open('StudentAchievements.txt', 'w', encoding='utf-8') as file:
                    json.dump(self.students, file)
                return True,'{}用户数据修改成功'.format(stu["name"])
        return False,'{}用户数据修改失败'.format(stu["name"])





#把数据放到这里
db=MysqlDatabases()

if __name__ == '__main__':
    # print(db.check_login('admin1','123456'))
    # print(db.all())
    print(db.search_by_username('梁晨111'))